# $Id: netdot.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

# Python imports
from optparse import make_option

# Third party imports
from django.core.management.base import BaseCommand, CommandError
from django.db import connection

# Local imports
from djanet.core import ip

## Command class, inherits BaseCommand
class Command(BaseCommand):
   # Construct command line options for this command
   option_list = BaseCommand.option_list + (
         make_option("-a", "--all", help = "Get all devices",
            dest = "all", action = "store_true"),
         make_option("-s", "--site", help = "Get devices from a site",
            type = "choice", choices = ("Layer42", "AIS"), dest = "site"),
         make_option("-i", "--interface",
            help = "Print interface information from netdot",
            dest = "interface"),
         )

   # Help command
   help = "Get devices/interface information from netdot"

   required_model_validation = False

   ## Handle the command line options
   def handle(self, **options):
      OptionAll = options.get("all")
      OptionSite = options.get("site")
      OptionInterface = options.get("interface")
      interface = False
      sqlQuery = None

      if OptionInterface:
         sqlQuery = "select interface.name, ipblock.address from interface "
         sqlQuery += "left join device on device.id = interface.device "
         sqlQuery += "left join ipblock on ipblock.id = device.snmp_target;"
         interface = True
      else:
         sqlQuery = "select site.name, rr.name, zone.mname, community, "
         sqlQuery += "product.name, ipblock.address from device "
         sqlQuery += "left join site on site.id = device.site left join "
         sqlQuery += "product on product.id = device.product left join "
         sqlQuery += "ipblock on ipblock.id = device.snmp_target "
         sqlQuery += "left join rr on rr.id = device.name "
         sqlQuery += "left join zone on zone.id = rr.zone "

         if OptionSite:
            sqlQuery += "where site.name = '%s';" %OptionSite

         if OptionAll:
            sqlQuery += ";"

      cursor = connection.cursor()
      if cursor.execute(sqlQuery):
         if interface:
            for values in cursor.fetchall():
               temp = values[-1]
               address = None
               if temp:
                  try:
                     address = ip.ip(int(temp))
                     if str(address) == OptionInterface:
                        print "%s %s" %(values[0], address)
                  except exception.IPError, message:
                     raise CommandError, message
         else:
            for values in cursor.fetchall():
               temp = values[-1]
               address = None
               if temp:
                  try:
                     address = ip.ip(int(temp))
                     print "%s %s %s %s %s %s" %(values[0], values[1],
                           values[2], values[3], values[4], address)
                  except exception.IPError, message:
                     raise CommandError, message
               else:
                  print "%s %s %s %s %s" %(values[0], values[1], values[2],
                        values[3], values[4])
